//
//  HMSelectPeriodCalendarVC.m
//  HotelManager
//
//  Created by r on 17/4/21.
//  Copyright © 2017年 Xun. All rights reserved.
//

#import "HMSelectPeriodCalendarVC.h"
#import "HMSelectPeriodCell.h"
#import "NSDateComponents+Calendar.h"

#define kCollectWidth (kScreenWidth / 7.0)
#define kCollectHeight kScaleNum(70)

@interface HMSelectPeriodCalendarVC ()<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property (nonatomic, strong) UIView *topView;//!<
@property (nonatomic, strong) UILabel *dateLab;//!<日期
@property (nonatomic, strong) UIButton *lastBtn;//!<上一月按钮
@property (nonatomic, strong) UIButton *nextBtn;//!<下一月按钮
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIView *bottomView;

@property (nonatomic, strong) NSCalendar *calendar;//!<日历
@property (nonatomic, strong) NSDateComponents *todayComponents;//!<今天components
@property (nonatomic, strong) NSDateComponents *showingComponents;//!<当前显示月份的第一天components

@property (nonatomic, strong) NSDateComponents *selectStartComp;//!<选中的开始components
@property (nonatomic, strong) NSDateComponents *selectEndComp;//!<选中的结束components

@property (nonatomic, strong) NSArray *dateCompArr;
@property (strong, nonatomic) UIButton *confirmBtn;

@end

@implementation HMSelectPeriodCalendarVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setNavigationItemBackBBIAndTitle:@"日期"];
    [self updateConstraintsForCollectionView];
}

- (void)initData {
    
    self.todayComponents = [self.calendar components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday) fromDate:[NSDate date]];
    
    if (self.showDay.length > 0) {
        NSArray *arr = [self.showDay componentsSeparatedByString:@"-"];
        if (arr.count > 2) {
            self.todayComponents.year = [arr[0] intValue];
            self.todayComponents.month = [arr[1] intValue];
            self.todayComponents.day = [arr[2] intValue];
            [self setSelectStartComp:self.todayComponents];
        }
    }
    
    self.showingComponents = [[NSDateComponents alloc] init];
    self.showingComponents.year = self.todayComponents.year;
    self.showingComponents.month = self.todayComponents.month;
    self.showingComponents.day = 1;
    
    self.dateCompArr = [NSDateComponents dateCompontentsWithSomedayComponents:self.todayComponents];
    self.dateLab.text = [NSString stringWithFormat:@"%ld-%02ld",(long)self.todayComponents.year, (long)self.todayComponents.month];
    
    if (self.showDay.length > 0) {
        [self setSelectStartComp:self.todayComponents];
    }
}

#pragma mark - Private Methods

- (void)updateConstraintsForCollectionView {
    
    NSInteger row = self.dateCompArr.count / 7 ;
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(kCollectHeight * row + 1);
    }];
}

#pragma mark - Event Response

- (void)clickLastBtn {
    
    self.showingComponents = [NSDateComponents dateComponents:self.showingComponents AfterYears:0 months:-1 days:0];
    self.dateCompArr = [NSDateComponents dateCompontentsWithSomedayComponents:self.showingComponents];
    [self.collectionView reloadData];
    
    self.dateLab.text = [NSString stringWithFormat:@"%ld-%02ld",(long)self.showingComponents.year, (long)self.showingComponents.month];
    [self updateConstraintsForCollectionView];
}

- (void)clickNextBtn {
    
    self.showingComponents = [NSDateComponents dateComponents:self.showingComponents AfterYears:0 months:1 days:0];
    self.dateCompArr = [NSDateComponents dateCompontentsWithSomedayComponents:self.showingComponents];
    [self.collectionView reloadData];
    
    self.dateLab.text = [NSString stringWithFormat:@"%ld-%02ld",(long)self.showingComponents.year, (long)self.showingComponents.month];
    [self updateConstraintsForCollectionView];
}

-(void)clickedConfirmBtn {
    if (self.selectStartComp == nil) {
        [Prompt popPromptViewWithMsg:@"请选择日期" duration:2];
        return;
    }
    NSString *date = [NSString stringWithFormat:@"%zd-%zd-%zd",self.selectStartComp.year,self.selectStartComp.month,self.selectStartComp.day];
    !self.selectBlock ?: self.selectBlock(date);
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UICollectionViewDataSource

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dateCompArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    HMSelectPeriodCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HMSelectPeriodCell" forIndexPath:indexPath];
    NSDateComponents *dateComp = self.dateCompArr[indexPath.row];
    
    if (self.lastDate == YES) { //可以选过去的日期
        if (dateComp.year != self.showingComponents.year || dateComp.month != self.showingComponents.month) {// 非本月日期
            [cell refreshCellWithDay:0 cellType:PeriodCellType_Blank];
            
        }else if (dateComp.year == self.selectStartComp.year && dateComp.month == self.selectStartComp.month && dateComp.day == self.selectStartComp.day) {// 选中的开始日
            [cell refreshCellWithDay:dateComp.day cellType:PeriodCellType_Start];
            
        }else {
            [cell refreshCellWithDay:dateComp.day cellType:PeriodCellType_Future];
        }
        return cell;
    }
    
    if (dateComp.year != self.showingComponents.year || dateComp.month != self.showingComponents.month) {// 非本月日期
        [cell refreshCellWithDay:0 cellType:PeriodCellType_Blank];
        
    } else if (NSOrderedAscending != [[self.calendar dateFromComponents:dateComp] compare:[self.calendar dateFromComponents:self.todayComponents]] ) {// 今日()以后
        [cell refreshCellWithDay:dateComp.day cellType:PeriodCellType_Future];
        
        if (dateComp.year == self.selectStartComp.year && dateComp.month == self.selectStartComp.month && dateComp.day == self.selectStartComp.day) {// 选中的开始日
            [cell refreshCellWithDay:dateComp.day cellType:PeriodCellType_Start];
            
        } else if (dateComp.year == self.selectEndComp.year && dateComp.month == self.selectEndComp.month && dateComp.day == self.selectEndComp.day) {// 选中的结束日
            [cell refreshCellWithDay:dateComp.day cellType:PeriodCellType_End];
        }
        
    } else {// 本月
        [cell refreshCellWithDay:dateComp.day cellType:PeriodCellType_Normal];
    }
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDateComponents *dateComp = self.dateCompArr[indexPath.row];
    if (self.maxDay.length > 0) {
        NSArray *arr = [self.maxDay componentsSeparatedByString:@"-"];
        if (arr.count > 2) {
            NSDateComponents *maxComponents = [[NSDateComponents alloc] init];
            maxComponents.year = [arr[0] intValue];
            maxComponents.month = [arr[1] intValue];
            maxComponents.day = [arr[2] intValue];
            if (NSOrderedAscending == [[self.calendar dateFromComponents:maxComponents] compare:[self.calendar dateFromComponents:dateComp]]) {//超过最大日期
                [Prompt popPromptViewWithMsg:@"不能大于截止日期!" duration:2];
                return;
            }
        }
    }
    if (self.minDay.length > 0) {
        NSArray *arr = [self.minDay componentsSeparatedByString:@"-"];
        if (arr.count > 2) {
            NSDateComponents *minComponents = [[NSDateComponents alloc] init];
            minComponents.year = [arr[0] intValue];
            minComponents.month = [arr[1] intValue];
            minComponents.day = [arr[2] intValue];
            if (NSOrderedDescending == [[self.calendar dateFromComponents:minComponents] compare:[self.calendar dateFromComponents:dateComp]]) {//超过最大日期
                [Prompt popPromptViewWithMsg:@"不能小于开始日期!" duration:2];
                return;
            }
        }
    }
    
    if (self.lastDate == YES) {
        if (dateComp.year != self.showingComponents.year || dateComp.month != self.showingComponents.month) {//非本月日期
            return;
        } else {
            self.selectStartComp = dateComp;
        }
    }else {
        if (NSOrderedDescending == [[self.calendar dateFromComponents:self.todayComponents] compare:[self.calendar dateFromComponents:dateComp]]) {// 今天以前不可选
            return;
        } else {
            self.selectStartComp = dateComp;
        }
    }
}

#pragma mark - 搭建UI

- (void)initUI {
    
    [self.view addSubview:self.topView];
    [self.view addSubview:self.collectionView];
    [self.view addSubview:self.bottomView];
    [self addRightViews:@[self.confirmBtn]];
    
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(kScaleNum(StatusHeight)));
        make.left.right.equalTo(@0);
        make.height.mas_equalTo(kScaleNum(75));
    }];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(@0);
        make.top.equalTo(self.topView.mas_bottom);
        make.height.mas_equalTo(kCollectHeight * 5);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(@0);
        make.top.equalTo(self.collectionView.mas_bottom);
    }];
    
    [self.topView addSubview:self.dateLab];
    [self.topView addSubview:self.lastBtn];
    [self.topView addSubview:self.nextBtn];
    
    [self.dateLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@(kScaleNum(16)));
        make.centerX.equalTo(@0);
    }];
    
    [self.lastBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.dateLab.mas_left).with.offset(kScaleNum(-25));
        make.centerY.equalTo(self.dateLab);
        make.size.mas_equalTo(SASizeMake(40, 30));
    }];
    
    [self.nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.dateLab.mas_right).with.offset(kScaleNum(25));
        make.centerY.equalTo(self.dateLab);
        make.size.mas_equalTo(SASizeMake(40, 30));
    }];
    
    NSArray *weekDay = @[@"日", @"一", @"二", @"三", @"四", @"五", @"六"];
    CGFloat labWidth = self.view.width / weekDay.count;
    for (NSInteger i = 0; i < weekDay.count; i++) {
        UILabel *lab = [[UILabel alloc] init];
        lab.textColor = [UIColor whiteColor];
        lab.font = kFont(12);
        lab.text = weekDay[i];
        lab.textAlignment = NSTextAlignmentCenter;
        [self.topView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(@(labWidth * i));
            make.bottom.equalTo(@(0));
            make.size.mas_equalTo(CGSizeMake(labWidth, kScaleNum(25)));
        }];
    }
}

#pragma mark - Setters
- (void)setSelectStartComp:(NSDateComponents *)selectStartComp {
    _selectStartComp = selectStartComp;
    [self.collectionView reloadData];
}


#pragma mark - Getters

- (UIView *)topView{
    if (!_topView){
        _topView = [[UIView alloc] init];
        _topView.backgroundColor = kRedColor;
    }
    return _topView;
}

- (UILabel *)dateLab{
    if (!_dateLab){
        _dateLab = [[UILabel alloc] init];
        _dateLab.textColor = [UIColor whiteColor];
        _dateLab.font = kFont(16);
    }
    return _dateLab;
}

- (UIButton *)lastBtn{
    if (!_lastBtn){
        _lastBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_lastBtn setImage:[UIImage imageNamed:@"arrow4-w-l"] forState:UIControlStateNormal];
        [_lastBtn addTarget:self action:@selector(clickLastBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _lastBtn;
}

- (UIButton *)nextBtn{
    if (!_nextBtn){
        _nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_nextBtn setImage:[UIImage imageNamed:@"arrow4-w-r"] forState:UIControlStateNormal];
        [_nextBtn addTarget:self action:@selector(clickNextBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _nextBtn;
}

- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        layout.sectionInset = UIEdgeInsetsMake(1, 0, 1, 0);
        layout.minimumInteritemSpacing = 0;
        layout.minimumLineSpacing = 0;
        layout.itemSize = CGSizeMake(kCollectWidth, kCollectHeight);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.bounces = NO;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[HMSelectPeriodCell class] forCellWithReuseIdentifier:@"HMSelectPeriodCell"];
        _collectionView.backgroundColor = [UIColor whiteColor];
    }
    return _collectionView;
}

- (UIView *)bottomView {
    if (!_bottomView) {
        _bottomView = [[UIView alloc] init];
        _bottomView.backgroundColor = [UIColor whiteColor];
    }
    return _bottomView;
}

- (NSCalendar *)calendar {
    if (!_calendar) {
        _calendar = [NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian];
    }
    return _calendar;
}

-(UIButton *)confirmBtn {
    if (!_confirmBtn) {
        _confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_confirmBtn setTitle:@"确认" forState:UIControlStateNormal];
        [_confirmBtn setTitleColor:kBuleColor forState:UIControlStateNormal];
        _confirmBtn.frame = SARectMake(0, 0, 63, 44);
        [_confirmBtn addTarget:self action:@selector(clickedConfirmBtn) forControlEvents:UIControlEventTouchUpInside];
    }
    return _confirmBtn;
}


@end
